package com.mainbo.androidframework.net.Retrofit;

import android.text.TextUtils;


import com.mainbo.androidframework.App;
import com.mainbo.androidframework.utils.JsonUtility;
import com.mainbo.androidframework.utils.LogUtil;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import retrofit.JacksonConverterFactory;
import retrofit.Retrofit;

/**
 * Retrofit帮助类
 * Created by wei-pc on 2015/11/26.
 */
public class RetrofitUtils {
    public static final String API_URL = "";
    public static final String CLIENT_ID = "";
    public static final String CLIENT_SECRET="";
    private static long mTimeOut = 10;
    private static Retrofit retrofit;
    private static Map<Class, Object> mServiceMap = new HashMap<>();
    /**
     * not refreshToken Interceptor
     */
    private static Interceptor mInterceptorWithoutRefresh = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            //TokenInfo tokenInfo = GlobalPreferStore.getTokenInfo();
            Request.Builder builder = request.newBuilder()
                    .addHeader("Content-Type", "application/x-www-form-urlencoded");
            /*if (tokenInfo != null && !TextUtils.isEmpty(tokenInfo.mAccessToken)) {
                builder.addHeader("Authorization", "Bearer " + tokenInfo.mAccessToken);
            }*/
            request = builder.build();
            LogUtil.i("NET", "request : " + request.toString());
            Response response = chain.proceed(request);
//            LogUtil.i("NET", response.newBuilder().build().body().string());
            return response;
        }
    };

    private static Interceptor mInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            //TokenInfo tokenInfo = GlobalPreferStore.getTokenInfo();
            Request.Builder builder = request.newBuilder()
                    .addHeader("Content-Type", "application/x-www-form-urlencoded");
            /*if (tokenInfo != null && !TextUtils.isEmpty(tokenInfo.mAccessToken)) {
                  builder.removeHeader("Authorization");
                builder.addHeader("Authorization", "Bearer " + tokenInfo.mAccessToken);
            }*/
            request = builder.build();
            LogUtil.i("NET", "request : " + request.toString());
            Response response = chain.proceed(request);
//            LogUtil.i("NET", "response : " + response.newBuilder().build().body().string());
            //token date off
            /*if (tokenInfo != null && response.code() == 401) {
                LogUtil.w("NET", "token unauthorization and refresh token");
                OkHttpClient okHttpClient = new OkHttpClient();
                okHttpClient.setConnectTimeout(mTimeOut, TimeUnit.SECONDS);
                okHttpClient.networkInterceptors().add(mInterceptorWithoutRefresh);
                Retrofit refreshRetrofit = new Retrofit.Builder()
                        .addCallAdapterFactory(new CustomCallAdapter.CustomCallAdapterFactory())
                        .baseUrl(API_URL)
                        .client(okHttpClient)
                        .addConverterFactory(JacksonConverterFactory.create(JsonUtility.getObjectMapper()))
                        .build();
                refreshRetrofit.client().setConnectTimeout(mTimeOut, TimeUnit.SECONDS);
                AccountNetService accountService = refreshRetrofit.create(AccountNetService.class);
                try {
                    retrofit.Response<TokenInfo> refreshResponse = accountService.getOauthToken(GrantType.REFRESH_TOKEN.id,
                            tokenInfo.mRefreshToken, CLIENT_ID, CLIENT_SECRET).execute();
                    if (refreshResponse.code() == 401) {
                        LogUtil.w("NET", "refresh token unauthorization and logout to LoginActivity");
                        LoginUtils.logoutToLoginAct(App.mContext);
                    } else if (refreshResponse.isSuccess()) {
                        LogUtil.w("NET", "get new token and redo request");
                        tokenInfo = refreshResponse.body();
                        if (tokenInfo != null) {
                            GlobalPreferStore.saveTokenInfo(tokenInfo);
                            response = chain.proceed(request);
                        }
                    } else {
                        LogUtil.w("NET", "get new token failsed errorCode : " + refreshResponse.code());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }*/
            return  response;
        }
    };

    static {
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(mTimeOut, TimeUnit.SECONDS);
        client.interceptors().add(mInterceptor);
        retrofit = new Retrofit.Builder()
                .baseUrl(API_URL)
                .client(client)
                .addCallAdapterFactory(new CustomCallAdapter.CustomCallAdapterFactory())
                .addConverterFactory(JacksonConverterFactory.create(JsonUtility.getObjectMapper()))
                .build();
    }

    public static Retrofit getRetrofit() {
        return retrofit;
    }

    public static <T> T create(Class<T> tClass) {
        return retrofit.create(tClass);
    }

    /**
     * get Service
     *
     * @param tClass service type
     * @param <T>    service type
     * @return 服务
     */
    public static <T> T getService(Class<T> tClass) {
        if (tClass == null) return null;
        T t = (T) mServiceMap.get(tClass);
        if (t == null) {
            t = create(tClass);
            mServiceMap.put(tClass, t);
        }
        return t;
    }
}
